package com.gitee.cnlongdb.server.connect.nettymission.operator;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.gitee.cnlongdb.basic.constant.LongDbConstant;
import com.gitee.cnlongdb.basic.entity.backups.LongdbBackupsEntity;
import com.gitee.cnlongdb.basic.entity.datasync.CnLongDataSyncRequest;
import com.gitee.cnlongdb.basic.entity.query.LongDbQuery;
import com.gitee.cnlongdb.basic.enums.sysnc.LongdbDataSyncEnms;
import com.gitee.cnlongdb.basic.utils.RandomUtil;
import com.gitee.cnlongdb.server.connect.LongDbConnect;

/**
 * 系统名称：NettyDataOperator.java
 * 模块名称：
 * 模块描述：处理服务端与客户端的数据往来
 * 功能列表：
 * 模块作者：ZOUYONG
 * 开发时间：2019年4月10日 下午10:30:26
 * 模块路径：com.gitee.cnlongdb.server.connect.nettymission.operator.NettyDataOperator
 * 更新记录：
 */
public class NettyDataOperator {

	private final Logger logger = (Logger) LoggerFactory.getLogger(NettyDataOperator.class);

	// 数据库连接对象
	private LongDbConnect connect;
	
	public NettyDataOperator(LongDbConnect connect) {
		this.connect = connect;
	}
	
	/**
	 * 功能描述：接收客户端请求
	 * 模块作者：ZOUYONG
	 * 开发时间：2019年4月10日 下午10:30:11
	 * 更新记录：
	 * 返回数据：String
	 */
	public String getNettyClientMessage(String message) {
		
		if(StringUtils.isBlank(message)) {
			return LongdbDataSyncEnms.cnlongNettySplitUnpooled.name();
		}
		
		Map<String, Object> requestMap = JSON.parseObject(message, Map.class);
		Object dataSyncType = requestMap.get(LongdbDataSyncEnms.dataSyncType.name());
		if(null == dataSyncType || StringUtils.isBlank(dataSyncType.toString())) {
			return LongdbDataSyncEnms.cnlongNettySplitUnpooled.name();
		}

		StringBuffer result = new StringBuffer();
		try {
			// cnlongdb - 执行中国龙数据库数据同步操作
			if(dataSyncType.toString().equals(LongDbConstant.longdbName))
			{
				result.append(executeLongDataSyncOperator(requestMap));
			}
			// 第三方系统数据同步操作
			else if(dataSyncType.toString().equals(LongdbDataSyncEnms.thirdSystem.name())) {
				Object jsonStr = requestMap.get(LongdbDataSyncEnms.dataSyncContent.name());
				if(null != jsonStr && StringUtils.isNotBlank(jsonStr.toString())) {
					result.append(executeThirdDataSyncOperator(jsonStr.toString()));
				}
			}
		}
		catch(Exception e) {
			result.append(e.getMessage());
			logger.error("协调同步数据异常：" + result.toString());
		}
		return result.append(LongdbDataSyncEnms.cnlongNettySplitUnpooled.name()).toString();
	}

	/**
	 * 功能描述：执行第三方系统-数据同步操作
	 * 模块作者：ZOUYONG
	 * 开发时间：2019年4月3日 下午10:06:58
	 * 更新记录：
	 * 返回数据：void
	 */
	private String executeThirdDataSyncOperator(String jsonStr) {
		
		CnLongDataSyncRequest request = JSON.parseObject(jsonStr, CnLongDataSyncRequest.class);
		Object operator = null;
		try {
			operator = Class.forName(request.getClassPath()).newInstance();
		} catch (Exception e) {
			logger.error("动态转换对象异常：" + e.getMessage());
			return e.getMessage();
		}
		
		Object object = null;
		try {
			Class[] cls = { Class.forName(request.getParamClas()[0]) };
			Object paramObject = JSON.parseObject(request.getParamObject()[0], cls[0]);
			object = operator.getClass()
				.getMethod(request.getMethodName(), cls)
				.invoke(operator, paramObject);
		} catch(Exception e) {
			logger.error("动态执行同步数据异常：" + e.getMessage());
			object = e.getMessage();
		}
		if(null != object) {
			return object.toString();
		}
		return "";
	}

	/**
	 * 功能描述：执行中国龙数据库数据同步操作
	 * 模块作者：ZOUYONG
	 * 开发时间：2019年4月3日 下午10:03:57
	 * 更新记录：
	 * 返回数据：void
	 */
	private String executeLongDataSyncOperator(Map<String, Object> requestMap) {

		StringBuffer requestResult = new StringBuffer();
		for(Iterator<String> iter = requestMap.keySet().iterator(); iter.hasNext(); ) {
			String bussType = iter.next();
			// 查询操作
			if(LongDbConstant.longdbActuatorQuery.equals(bussType)) 
			{
				LongDbQuery query = JSON.parseObject(requestMap.get(bussType).toString(), LongDbQuery.class);
				Object object = connect.getQueryOperator().findLocal(query);
				if(query.isQueryCount()) {
					requestResult.append(JSON.toJSONString(query));
				} else {
					requestResult.append(JSON.toJSONString(object));
				}
			}
			else if(LongDbConstant.longdbActuatorCreate.equals(bussType)	// 创建操作
					|| LongDbConstant.longdbActuatorRemove.equals(bussType)	// 删除操作
					|| LongDbConstant.longdbActuatorUpdate.equals(bussType)	// 修改操作
					|| LongDbConstant.longdbActuatorInsert.equals(bussType)	// 新增操作
			) {
				LongdbBackupsEntity backpups  = JSON.parseObject(requestMap.get(bussType).toString(), LongdbBackupsEntity.class);
				try {
					Object operator = null;
					if(LongDbConstant.longdbActuatorCreate.equals(bussType)){
						operator = connect.getCreateOperator();
					}
					else if(LongDbConstant.longdbActuatorRemove.equals(bussType)){
						operator = connect.getRemoveOperator();
					}
					else if(LongDbConstant.longdbActuatorUpdate.equals(bussType)){
						operator = connect.getUpdateOperator();
					}
					else if(LongDbConstant.longdbActuatorInsert.equals(bussType)){
						operator = connect.getInsertOperator();
					}
					else {
						throw new RuntimeException("远程同步操作不支持的操作类型!");
					}
					// 定义该操作是数据同步标识
					String transactionName = RandomUtil.getRandomNumber(24) + LongDbConstant.longdbMasterSlaveSynsFlag;
					Thread.currentThread().setName(transactionName);
					operator.getClass()
						.getMethod(backpups.getMethodName(), backpups.getParamClas())
						.invoke(operator, backpups.getParamObject());
					backpups.setOperStatus(true);
				} catch (Exception e) {
					backpups.setOperStatus(false);
					backpups.setOperMessage(e.getMessage());
					logger.error("远程同步操作异常" + e.getMessage());
				}
				requestResult.append(JSON.toJSONString(backpups));
			}
		}
		return requestResult.toString();
	}

}
